﻿using GreenXi.Model;
using Microsoft.Win32;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows.Forms;
using static GreenXi.App;

namespace GreenXi.ViewModel
{
    public class BackupInfoViewModel : BackupInfo
    {
        public BackupInfoViewModel()
        {
            CurrentFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Bcakup";
            CurrentFileName = "backup";
            BackupIntervalDay = GlobalVariables.BackupIntervalDay;
            BackupIntervalTime = GlobalVariables.BackupIntervalTime;
            BackupInfoList = GetBackupInfoList();
        }

        #region DelegateCommand
        private DelegateCommand _slectFolderPath;

        public DelegateCommand SlectFolderPath
        {
            get
            {
                if (_slectFolderPath == null)
                {
                    _slectFolderPath = new DelegateCommand(Slect_Executed);
                }
                return _slectFolderPath;
            }
        }

        private void Slect_Executed()
        {
            FolderBrowserDialog dialog = new();
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                CurrentFolderPath = dialog.SelectedPath;
            }
        }

        private DelegateCommand _backupDataBase;

        public DelegateCommand BackupDataBase
        {
            get
            {
                _backupDataBase ??= new DelegateCommand(Bcakup_Executed);
                return _backupDataBase;
            }
        }

        private void Bcakup_Executed()
        {
            BackupDirect(null, null);
        }

        //直接备份
        internal void BackupDirect(object? sender, ElapsedEventArgs? e)
        {
            //备份文件
            var backupFile = GetBackupFile();
            // 创建备份命令
            string backupCommand =
                $"{Util.ConnnectUtl.DbBackupStr}  --default-character-set=utf8 --single-transaction --routines --triggers --databases haina > \"{backupFile}\"";

            // 创建 ProcessStartInfo 对象
            ProcessStartInfo startInfo =
                new()
                {
                    FileName = "cmd.exe", //确定程序名
                    Arguments = $"/C \"{backupCommand}\"", //确定程式命令行
                    UseShellExecute = false, //Shell的使用
                    RedirectStandardInput = true, //重定向输入
                    RedirectStandardOutput = true, //重定向输出
                    RedirectStandardError = true, //重定向输出错误
                    CreateNoWindow = true, //设置置不显示示窗口
                    WorkingDirectory = GetMySqlPath() // 指定工作目录
                };
            //System.Windows.MessageBox.Show(startInfo.WorkingDirectory);
            // 创建 Process 对象并执行备份命令
            using Process process = new();
            process.StartInfo = startInfo;
            process.Start();
            //要加个进度条，不然定时备份执行时，这里有必要阻塞进程，所以不使用异步
            process.WaitForExit();
            BackupInfoList = GetBackupInfoList();
        }
        #endregion

        #region 数据获取

        public List<BackupInfo> GetBackupInfoList()
        {
            if (CurrentUser.RoleLevel < 3)
            {
                if (Directory.Exists(CurrentFolderPath))
                {
                    List<BackupInfo> _BackupInfoList = GetAllSqlFiles(CurrentFolderPath)
                        .Select(
                            x =>
                                new BackupInfo
                                {
                                    FileName = x.Name,
                                    FileSize = GetSize(x.Length),
                                    BackupTime = x.LastWriteTime.ToString("yyyy/MM/dd H:mm:ss")
                                }
                        )
                        .ToList();
                    return _BackupInfoList;
                }
                else
                {
                    Directory.CreateDirectory(CurrentFolderPath);
                    return new();
                }
            }
            else
            {
                return new List<BackupInfo>();
            }
        }

        // 将文件大小从字节转换为相应的单位
        public static string GetSize(long fileSize)
        {
            if (fileSize >= 1024 * 1024 * 1024) // 大于等于 1GB
            {
                return $"{(double)fileSize / (1024 * 1024 * 1024):f2}GB";
            }
            else if (fileSize >= 1024 * 1024) // 大于等于 1MB
            {
                return $"{(double)fileSize / (1024 * 1024):f2}MB";
            }
            else // 小于 1MB
            {
                return $"{(double)fileSize / 1024:f2}KB";
            }
        }

        // 获取指定路径下的所有 .sql 文件
        public static List<FileInfo> GetAllSqlFiles(string folderPath)
        {
            if (Directory.Exists(folderPath))
            {
                DirectoryInfo folder = new(folderPath);
                try
                {
                    FileInfo[] files = folder.GetFiles("*.sql", SearchOption.AllDirectories);
                    return files.ToList();
                }
                catch (Exception e)
                {
					Helpers.Logger.Instance.Warning($"Catch GetAllSqlFiles {e.Message}");
                    return new();
				}
            }
            else
            {
                return new();
            }
        }

        // 查找 MySQL 安装路径
        public static string GetMySqlPath()
        {
            string mysqlInstallPath = "";
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\MySQL AB\MySQL Server 5.7"))
            {
                if (key != null)
                {
                    object installDir = key.GetValue("Location") ?? "";
                    if (installDir != null)
                    {
                        mysqlInstallPath = installDir.ToString() ?? "";
                    }
                }
            }
            if (mysqlInstallPath != "")
            {
                return mysqlInstallPath + @"\bin";
            }
            else
            {
                System.Windows.MessageBox.Show("未找到 MySQL 安装路径");
                return "未找到 MySQL 安装路径";
            }
        }

        //获取备份文件
        public string GetBackupFile()
        {
            string dateTimeSuffix = DateTime.Now.ToString("yyyyMMddHHmmss");
            if (!Directory.Exists(CurrentFolderPath))
            {
                Directory.CreateDirectory(CurrentFolderPath);
            }
            if (Path.GetExtension(CurrentFileName) == ".sql" && CurrentFileName.IndexOf('.') == CurrentFileName.LastIndexOf('.'))
            {
                string newFileName = Path.GetFileNameWithoutExtension(CurrentFileName) + "_" + dateTimeSuffix + Path.GetExtension(CurrentFileName);
                return CurrentFolderPath + newFileName;
            }
            else if (CurrentFileName.IndexOf('.') == -1)
            {
                return CurrentFolderPath + @"\" + CurrentFileName + "_" + dateTimeSuffix + ".sql";
            }
            else
            {
                System.Windows.MessageBox.Show("文件名有问题");
                return "文件名有问题";
            }
        }

        #endregion
    }
}
